<script setup>
import { ref } from 'vue';
import myAxios from '../http';

const id = ref(1); // 查找的id
const student = ref({}); // 学生信息
const students = ref([]); // 学生列表

// 获取学生列表
myAxios.get('https://localhost:7002/api/students/getall').then(res => {
    // 这边写res即可，不用res.data了，自定义库里面处理过了
    students.value = res;
}).catch(error => {
    console.log(error.message);
})

// 根据id获取学生信息
const getDataById = () => {
    myAxios.get('https://localhost:7002/api/students/getstudent', {
        params: {
            id: id.value
        }
    }).then(res => {
        student.value = res;
    }).catch(error => {
        console.log(error.message);
    });
}
// 更新学生信息
const updateData = () => {
    myAxios.post('https://localhost:7002/api/students/update', {
        ...student.value
    }).then(res => {
        const index = students.value.findIndex(s => s.id == res.id);
        if (index != -1)
            students.value[index] = res;
    }).catch(error => {
        console.log(error.message);
    });
}
</script>

<template>
    <div>
        <div>
            <ul>
                <li v-for="student in students" :key="student.id">
                    {{ student.id }}.{{ student.name }}-{{ student.age }}-{{ student.gender }}
                </li>
            </ul>
        </div>
        <div>
            <input type="text" v-model="id"><button @click="getDataById">get请求获取id为{{ id }}的学生</button>
        </div>
        <div v-if="student.id">
            <input v-model="student.id" type="hidden" /><br />
            <input v-model="student.name" type="text" /><br />
            <input v-model="student.age" type="text" /><br />
            <input v-model="student.gender" type="text" /><br />
            <button @click="updateData">修改id为{{ student.id }}的信息</button>
        </div>
    </div>
</template>

<style scoped></style>